# -*- coding: utf-8 -*-
"""
Created on Thu Apr 23 15:23:00 2020

@author: zdr
"""

# -*- coding: utf-8 -*-
# @Date   : 2020/3/21
# @File   : IC01_Past6MonQueryCnt_2D.py
# @Author : zhaochen
'''eof
name:最近6个月的查询机构数
code:IC01_Past6MonQueryCnt_2D
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import sys
import re
import datetime
import pandas as pd


reload(sys)
sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--']

def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
        '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def dateFormat(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d')
                except:
                    date = None
    return date

def IC01_Past6MonQueryCnt_2D():
    data = IC_DSJ_2D.get('data')
    # 查询记录  POQ  [1..1]
    POQ = getTable(data, 'POQ', 1, 0)
    if POQ == [{}]:
        return u'缺失值'
    elif POQ == 0:
        return 0
    else:
        # 查询记录信息单元  PH01  [0..*]
        PH01 = getTable(POQ[0], 'PH01', 0, 1)
        if PH01 == [{}]:
            return u'缺失值'
        elif PH01 == 0:
            return 0
        else:
            result = []
            sixMonthsAgo = datetime.datetime.now() - pd.tseries.offsets.DateOffset(months=6)
            for i in PH01:
                PH010Q03 = i.get("PH010Q03")
                PH010Q02 = i.get("PH010Q02")
                PH010R01 = i.get("PH010R01")
                PH010R01 = dateFormat(PH010R01)

                if PH010Q03 not in null_type_list and PH010Q02 not in null_type_list and PH010R01 not in null_type_list :
                    if PH010Q03 in [02,03,'02','03'] and PH010R01 > sixMonthsAgo and PH010R01 <= datetime.datetime.now():
                        result.append(PH010Q02)
                    else:
                        result.append(0)
                else:
                    result.append(None)

            result = list(filter(lambda x:x is not None, result))
            if len(result) == 0:
                return u'缺失值'
            else:
                result = list(filter(lambda x: x != 0, result))
                return len(set(result))
if __name__ == '__main__':
    file_obj = open(r'E:\\IC_DSJ_2D.json', 'r')
    ratingRequest = {"legalPerson": u"朱为广", "legalPersonIdCard": "510102196706108511", "creditCode": "123456",
                     "regNumber": "12345", "relativeDate": u'2019/08/09'}
    content = file_obj.read()
    IC_DSJ_2D = json.loads(content, strict=False)
    print IC01_Past6MonQueryCnt_2D()

result = IC01_Past6MonQueryCnt_2D()


